﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ALDIOrganizer
{    
    public partial class DataFile
    {
        public Exception SaveTo(FileStream pFileStream)
        {
            using (pFileStream)
            {
                try
                {
                    OnTemplatesCollectionModified = null;
                    OnRotasCollectionModified = null;
                    OnLeavingModifiedEntity = null;
                    pFileStream.Seek(0, SeekOrigin.Begin);
                    var binary = new BinaryFormatter();
                    binary.Serialize(pFileStream, this);
                    Modified = false; // it'pShift saved now
                }
                catch (Exception ex)
                {
                    return ex;
                }
                finally
                {                    
                    pFileStream.Close();
                }
            }
            return null;
        }

        public static KeyValuePair<Exception, DataFile> LoadFrom(string pFileName)
        {
            DataFile retrieved;
            try
            {
                using (var stream = File.OpenRead(pFileName))
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    var binary = new BinaryFormatter();
                    retrieved = (DataFile)binary.Deserialize(stream);
                    retrieved.ComputeHolidays(-1);
                    retrieved.ActivateAll();
                    retrieved.FileName = pFileName;
                    return new KeyValuePair<Exception, DataFile>(null, retrieved);
                }
            }
            catch (Exception ex)
            {
                return new KeyValuePair<Exception, DataFile>(
                    ex,
                    null);
            }
        }

    }
}
